import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { MTLLoader } from "three/examples/jsm/loaders/MTLLoader.js";
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader.js";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

//创建场景
const scene = new THREE.Scene();

//创建相机
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);

//创建渲染器
const renderer = new THREE.WebGLRenderer({
  //抗锯齿
  antialias: true
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor("#d8dede", 1);
document.body.appendChild(renderer.domElement);
// 创建轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);

//创建环境光
const ambientLight = new THREE.AmbientLight(0xffffff);
//添加到场景
scene.add(ambientLight);

const pointLight = new THREE.PointLight(0xffffff, 15);
//添加至相机
camera.add(pointLight);

// 加载.gltf模型
// const loader = new GLTFLoader();
// loader.load(
//   "/public/models/gltf/33eqw.skp.gltf",
//   function(gltf) {
//     scene.add(gltf.scene);
//   },
//   function(xhr) {
//     // 加载进度回调
//     console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
//   },
//   function(error) {
//     console.error(error);
//   }
// );

// 加载 OBJ 文件所用
const loader = new OBJLoader();
// 加载 MTL 外衣所以
const MTLloader = new MTLLoader();

MTLloader.load("/public/models/IronMan/IronMan.mtl", function(materials) {
  materials.preload();
  for (const material of Object.values(materials.materials)) {
    // 设置材质双面
    material.side = THREE.DoubleSide;
  }
  // 给模型穿衣服
  loader.setMaterials(materials);

  //设置模型大小
  loader.load("/public/models/IronMan/IronMan.obj", function(obj) {
    // 模型加入到 scene
    obj.scale.set(1.0, 1.0, 1.0);
    obj.position.set(1.0, -100, 1.0);
    scene.add(obj);
  });
});

//设置相机位置
camera.position.set(1, 1, 400);

//渲染场景
function animate() {
  requestAnimationFrame(animate);
  // cube.rotation.x += 0.01;
  // cube.rotation.y += 0.01;
  renderer.render(scene, camera);
  controls.update();
}

animate();
